package com.wcgksoft.common.base;

import com.wcgksoft.common.util.FastJSONUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 阿良
 * @version 1.0.0
 * @ClassName ExController.java
 * @Description TODO
 * @createTime 2020年03月04日 23:14:00
 */
public abstract class ExController  {
  /**
   * 登录认证异常
   */
  @ExceptionHandler({UnauthenticatedException.class, AuthenticationException.class})
  public String authenticationException(HttpServletRequest request, HttpServletResponse response) {
    if (WebUtilsPro.isAjaxRequest(request)) {
      // 输出JSON
      Map<String, Object> map = new HashMap<>();
      map.put("code", "-999");
      map.put("message", "未登录");
      writeJson(map, response);
      return null;
    } else {
      return "redirect:/";
    }
  }

  /**
   * 权限异常
   */
  @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
  public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
    if (WebUtilsPro.isAjaxRequest(request)) {
      // 输出JSON
      Map<String, Object> map = new HashMap<>();
      map.put("code", "-998");
      map.put("message", "无权限");
      writeJson(map, response);
      return null;
    } else {
      return "redirect:/roleeqq";
    }
  }

  /**
   * 输出JSON
   *
   * @param response
   * @author 阿良
   * @create 2020年3月4日
   */
  private void writeJson(Map<String, Object> map, HttpServletResponse response) {
    PrintWriter out = null;
    try {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/json; charset=utf-8");
      out = response.getWriter();
      out.write(FastJSONUtils.mapTojson(map));
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }


}
